import {installIpcMain} from "./ipcMain";
import {IsUseSysTitle, openDevTools, UseStartupChart} from "../config/const";
import menuconfig from "../hook/menuHook";
import {app, BrowserWindow, Menu} from "electron";
import {loadingURL, winURL} from "../config/staticPath";
import {mainWindowConfig} from "../config/windowsConfig";
import hotkeysHook from "../hook/hotkeysHook";
import {useProcessException} from "../hook/exceptionHook";
import {openDevTools as openDevToolsFunc} from "../hook/devToolHook";

import path from "path";
import * as fs from "node:fs";

const sourceFile = app.isPackaged ? path.resolve(app.getAppPath(), '../../debug.txt') : path.join(__dirname, '../../../debug.txt');
let isDebug = false;
if (fs.existsSync(sourceFile)) {
	isDebug = true;
}

class MainInit {
	public winURL: string = "";
	public shartURL: string = "";
	public loadWindow: BrowserWindow = null;
	public mainWindow: BrowserWindow = null;

	constructor() {
		this.winURL = winURL;
		this.shartURL = loadingURL;
		// 开发环境或者设置了打开开发者模式时
		if (process.env.NODE_ENV === "development" || openDevTools || isDebug) {
			menuconfig.push({
				label: "开发者设置",
				submenu: [
					{
						label: "切换到开发者模式",
						accelerator: "CmdOrCtrl+I",
						click: () => openDevToolsFunc(BrowserWindow.getFocusedWindow()),
					},
				],
			});
		}
		// 启用协议
		installIpcMain();
	}

	createMainWindow() {
		this.mainWindow = new BrowserWindow({
			titleBarStyle: IsUseSysTitle ? "default" : "hidden",
			...Object.assign(mainWindowConfig, {}),
		});
		//注册全局快捷键
		hotkeysHook(this.mainWindow);
		// 赋予主菜单模板
		const menu = Menu.buildFromTemplate(menuconfig as any);
		// 加载模板
		Menu.setApplicationMenu(menu);
		// 加载主窗口
		this.mainWindow.loadURL(this.winURL);
		// ready-to-show之后显示界面
		this.mainWindow.once("ready-to-show", () => {
			this.mainWindow.show();
			// 开发模式下自动开启devtools
			if (process.env.NODE_ENV === "development" || isDebug) {
				openDevToolsFunc(this.mainWindow);
			}
			if (UseStartupChart) this.loadWindow.destroy();
		});
		// 对进程进行监控处理（响应假死等状态）
		useProcessException().renderProcessGone;
		useProcessException().childProcessGone;

		this.mainWindow.on("closed", () => {
			this.mainWindow = null;
		});
	}

	// 加载窗口函数
	loadingWindow(loadingURL: string) {
		this.loadWindow = new BrowserWindow({
			width: 400,
			height: 600,
			frame: false,
			skipTaskbar: true,
			transparent: true,
			resizable: false,
			webPreferences: {experimentalFeatures: true},
		});

		this.loadWindow.loadURL(loadingURL);
		this.loadWindow.show();
		this.loadWindow.setAlwaysOnTop(true);
		// 延迟两秒可以根据情况后续调快，= =，就相当于个，sleep吧，就那种。 = =。。。
		setTimeout(() => {
			this.createMainWindow();
		}, 1500);
	}

	// 初始化窗口函数
	initWindow() {
		if (UseStartupChart) {
			return this.loadingWindow(this.shartURL);
		} else {
			return this.createMainWindow();
		}
	}
}

export default MainInit;
